<?php
namespace app\backend\controller;
use app\backend\model\ProductCategoryModel;
use app\backend\model\ProductModel;
use app\backend\model\ProductSpecModel;
use app\common\model\ProductCategory;

/**
 * 登录类
 * @author Ray 541720500@qq.com
 */
class Product extends Base
{
    public function index()
    {
        $where = [];
        if(input('name')) {
            array_push($where, ['name', 'like', '%'.input('name').'%']);
        }
        if(input('suk')) {
            array_push($where, ['id', 'in', ProductSpecModel::where('suk', input('suk'))->column('goods_id') ]);
        }
        if(input('store')) {
            array_push($where, ['store_id', '=', \app\common\model\Store::where('name', input('store'))->value('id') ]);
        }

        $no_stock = ProductSpecModel::where('stock', 0)->group('goods_id')->column('goods_id');
        $not_enough = ProductSpecModel::where('stock', '<', 10)->group('goods_id')->column('goods_id');

        if(input('?type')) {
            switch (input('type')) {
                case 1:
                    array_push($where, ['status', '=', 1 ]);
                    break;
                case 2:
                    array_push($where, ['status', '=', 0 ]);
                    break;
                case 3:
                    array_push($where, ['id', 'in', $no_stock ]);
                    break;
                case 4:
                    array_push($where, ['id', 'in', $not_enough ]);
                    break;
            }
        }

        $this->assign('data', [
            'title' => '产品与服务',
            'collection' => ProductModel::with('spec')->where($where)->order('id desc')->paginate(config('paginate.per_page')),
            'thead' => [
                ['#','width:30px'],
                ['图片','width:100px'],
                '名称',
                ['','width:130px'],
                ['价格','width:100px'],
                ['库存','width:100px'],
                ['销量','width:100px'],
                ['状态','width:100px']
            ],
            'fields' => ['id',function($row) {
                return '<image src="'.$row['image'].'" class="image-in-td">';
            },'name',
                function($row) {
                    $txt = '';
                    foreach ($row->spec as $s) {
                        $txt.='规格：'. $s->suk . '<br/>';
                    }
                    return $txt;
                },
                function($row) {
                    $txt = '';
                    foreach ($row->spec as $s) {
                        $txt.= '￥' . $s->price . '<br/>';
                    }
                    return '<div style="text-align: right;">'. $txt . '</div>';
                },
                function($row) {
                    $txt = '';
                    foreach ($row->spec as $s) {
                        $txt.= ($s->stock < 10 ? ('<span style="color: red; font-weight: bold">'. $s->stock.'</span>') : $s->stock) . '<br/>';
                    }
                    return $txt;
                },
                function($row) {
                    $txt = '';
                    foreach ($row->spec as $s) {
                        $txt.= $s->sale_num . '<br/>';
                    }
                    return $txt;
                },
                'status'
            ],
            'buttons' => [
                ['title'=>'修改', 'onclick' => 'showBigWindow', 'url'=> url('create')], // 'onclick'=>'redirect',
                ['title'=>'价格规格','url'=> url('editSpec')],
                ['title'=>'上下架','onclick'=>'ajaxReq','url'=> url('switchStatus')],
//                ['title'=>'操作','type'=>'group', 'act' => [
//                    ['title'=>'上架','onclick'=>'ajaxReq','url'=> url('switchStatus')],
//                    ['title'=>'下架','onclick'=>'ajaxReq','url'=> url('switchStatus')],
//                ]],
            ],
            'mbuttons' => [
                ['title'=>'添加商品', 'onclick' => 'showBigWindow', 'url'=> url('create')],
            ],
            'searcher' => [
                ['type'=>'input','name'=>'name','placeholder'=>'商品名'],
                ['type'=>'input','name'=>'suk','placeholder'=>'规格名'],
                ['type'=>'input','name'=>'store','placeholder'=>'店铺名'],
            ],
            'tabs' => [
                ['title' => '全部', 'url' => url('index', ['type' => 0]), 'type' => 0], // 0 是默认
                ['title' => '已上架', 'url' => url('index', ['type' => 1]), 'type' => 1],
                ['title' => '未上架', 'url' => url('index', ['type' => 2]), 'type' => 2],
                ['title' => '已售罄 (' . count($no_stock) . ')', 'url' => url('index', ['type' => 3]), 'type' => 3],
                ['title' => '库存少 (' . count($not_enough) . ')', 'url' => url('index', ['type' => 4]), 'type' => 4],
            ]
        ]);
        return $this->fetch('public/table_builder');
    }
    public function create()
    {
        if(request()->isPost()) {
            $data = input('post.');
            $data['image'] = empty($data['image']) ? '' : $data['image'][0];
            $data['slider_image'] = empty($data['slider_image']) ? '' : json_encode($data['slider_image']);
//            var_dump($data);die;
            if(input('id')) {
                $this->modelUpdate('app\backend\model\ProductModel', $data, ['id' => $data['id']], 'product_saving');
            } else {
                $this->modelCreate('app\backend\model\ProductModel', $data, 'product_saving', '添加商品');
            }
        }else {
//            $this->assign('info','【商品价格】到规格里设置');
            return $this->fetchFormPageHtml('app\backend\model\ProductModel', __FUNCTION__);
        }
    }
    public function editSpec()
    {
        if(request()->isPost()) {
            $goods_id = input('goods_id/d');
            $input = input('post.');
            if($goods_id == null)
                $this->error('缺少商品ID');
            if(count($input['suk']) == 0)
                $this->error('未设置规格');

            $insert_data = [];
            foreach ($input['suk'] as $k => $v) {
                $insert_data[] = [
                    'id'        => $input['id'][$k],
                    'goods_id'  => $goods_id,
                    'suk'       => $input['suk'][$k],
                    'price'     => $input['price'][$k],
                    'stock'     => $input['stock'][$k],
                    'is_default'     => $k == 0 ? 1 : 0,
                ];
            }

            $res = ProductSpecModel::updateSpec($goods_id, $insert_data);
            if(true === $res) $this->success('已保存');
            else $this->error('保存出错');
        } else {
            $this->assign('list', ProductSpecModel::where('goods_id', input('id/d'))->where('is_del', 0)->select());
            return $this->fetch();
        }
    }
    public function switchStatus()
    {
        $res = ProductModel::changeStatus(input('id/d'));
        return $res['code'] == 1 ?  $this->success($res['msg']) : $this->error($res['msg']);
    }
    public function category()
    {
        $where = [];
        $list = ProductCategory::where($where)->order('id desc')->select()->toArray();
        $list = list2tree($list);
        foreach ($list as &$v) {
            $v['title'] = $v['prefix']. ' ' .$v['title'];
        }
        $this->assign('data', [
            'title' => '文章分类',
            'collection' => $list,
            'thead' => [
                ['#','width:60px'],
                '名称',
            ],
            'fields' => [
                'id','title'
            ],
            'buttons' => [
                ['title'=>'修改', 'onclick' => 'showBigWindow', 'url'=> url('createCategory')],
                ['title'=>'删除', 'onclick' => 'delOne', 'url'=> url('deleteCategory')],
            ],
            'mbuttons' => [
                ['title'=>'添加分类', 'onclick' => 'showBigWindow', 'url'=> url('createCategory')],
            ],
            'searcher' => [
                ['type'=>'input','name'=>'title','placeholder'=>'标题'],
            ],
        ]);
        return $this->fetch('public/table_builder');
    }
    public function createCategory()
    {
        $model = 'app\backend\model\ProductCategoryModel';
        if(request()->isPost()) {
            $data = input('post.');
            $data['parent_ids'] = $data['parent_id'] ? ProductCategoryModel::getPidsById($data['parent_id']) : 0;
            if($id = input('id')) {
                $this->modelUpdate($model, $data, ['id' => $data['id']], 'article_category_saving', '修改分类');
            } else {
                $this->modelCreate($model, $data, 'article_category_saving', '添加分类');
            }
        }else {
            return $this->fetchFormPageHtml($model, __FUNCTION__);
        }
    }
    public function deleteCategory()
    {
        $id = input('id');
        echo ProductCategory::destroy($id) ? 1 : 0;
    }

}
